import headerTapObj from 'dic/headerTaps';

export default {
  namespace: 'headerTaps',
  state: {
    panes: JSON.parse(localStorage.getItem('panes')) || [
      {
        title: '工作台',
        path: '/workBench',
        key: '/workBench',
        query: {}
      },
    ],
    currentTab: JSON.parse(localStorage.getItem('currentTab')) || {
      title: '工作台',
      path: '/workBench',
      key: '/workBench',
      query: {}
    },
  },

  effects: {
    // 更新panes
    *updatePanes({ payload: { pathname, query } }, { put, call, select }) {
      let panes = yield select(state => state.headerTaps.panes);
      const hasPane = panes.find(i => i.key === headerTapObj[pathname].key); // 查看是否已经存在pane
      yield put({
        type: 'updateCurrentTab',
        payload: {
          currentTab: {
            ...headerTapObj[pathname],
            query
          }
        },
      });
      if (!hasPane) {
        const arry = [...panes];
        arry.push({
          ...headerTapObj[pathname],
          query
        });
        yield put({
          type: 'updateHeaderTaps',
          payload: { panes: arry },
        });
      } else {
        const arr = panes.map(item => {
          if (item.key === hasPane.key) {
            item.query = query
          }
          return item
        })
        yield put({
          type: 'updateHeaderTaps',
          payload: { panes: arr },
        });
      }
    },
  },

  reducers: {
    // 更新panes
    updateHeaderTaps(state, { payload: { panes } }) {
      localStorage.setItem('panes', JSON.stringify(panes))
      return { ...state, panes };
    },
    // 更新currentTab
    updateCurrentTab(state, { payload: { currentTab } }) {
      localStorage.setItem('currentTab', JSON.stringify(currentTab))
      return { ...state, currentTab };
    },
  },
  subscriptions: {
    setup({ history, dispatch }) {
      return history.listen(({ pathname, query }) => {
        dispatch({ type: 'updatePanes', payload: { pathname, query } });
      });
    },
  },
};
